package cn.hbads.support.json.support;

import cn.hbads.support.context.SpringContextHolder;
import cn.hbads.support.error.ErrorType;
import cn.hbads.support.structure.result.ComputeResult;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * <b>Jackson的配置支持类，为ObjectMapper提供一些常用的配置或模块</b>
 *
 * @author yvvb
 * @date 2025/5/4
 * @apiNote 提供模块支持，提供默认、配置的ObjectMapper配置，注意需要配置系统变量dateTime.format、date.format、time.format否则使用默认的
 */
public final class JacksonConfigSupport {

    public static final String DATE_TIME_FORMAT_DEFAULT;
    public static final String DATE_FORMAT_DEFAULT;
    public static final String TIME_FORMAT_DEFAULT;

    static {
        String dateTimeFormat = System.getenv("dateTime.format");
        String dateFormat = System.getenv("date.format");
        String timeFormat = System.getenv("time.format");
        DATE_TIME_FORMAT_DEFAULT = StringUtils.isNotBlank(dateTimeFormat) ? dateTimeFormat : "yyyy-MM-dd HH:mm:ss";
        DATE_FORMAT_DEFAULT = StringUtils.isNotBlank(dateFormat) ? dateTimeFormat : "yyyy-MM-dd";
        TIME_FORMAT_DEFAULT = StringUtils.isNotBlank(timeFormat) ? dateTimeFormat : "HH:mm:ss";
    }

    private JacksonConfigSupport() {
    }

    public static ObjectMapper createConfigObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModules(getConfigJacksonModules());

        //总是包含字段
        safelySetSerialIncludeStrategy(objectMapper, JsonInclude.Include.ALWAYS);
        //null数组转换为[]
        safelySetSerialNullListToEmpty(objectMapper);

        //禁止特征： 序列化空对象失败、序列化将日期序列化为日期戳、反序列化在未知字段失败、日期类型添加时区信息
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        return objectMapper;
    }

    public static ObjectMapper createGenericObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModules(getGenericJacksonModules());

        safelySetSerialIncludeStrategy(objectMapper, JsonInclude.Include.ALWAYS);

        // 禁止特征： 序列化空对象失败、序列化时将日期序列化为时间戳，反序列化时在未知字段失败、日期类型添加时区信息
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        return objectMapper;
    }

    /**
     * @return {@link ObjectMapper} :返回Redis值/hash值序列化的ObjectMapper （key序列化用StringRedisSerializer就可以了）
     * @apiNote Redis的值序列化器Jackson2JsonRedisSerializer&lt;Object&gt;使用的ObjectMapper
     */
    public static ObjectMapper createRedisObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModules(getConfigJacksonModules());

        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return objectMapper;
    }


    public static ComputeResult<ObjectMapper, ErrorType> getContextObjectMapper() {
        return SpringContextHolder.getBean(ObjectMapper.class);
    }

    public static Set<Module> getConfigJacksonModules() {
        Set<Module> modules = new HashSet<>();
        modules.add(configJavaTimeModule());
        modules.add(jdk8Module());
//        modules.add(hibernate6Module());
        return modules;
    }

    public static Set<Module> getGenericJacksonModules() {
        Set<Module> modules = new HashSet<>();
        modules.add(defaultJavaTimeModule());
        modules.add(jdk8Module());
//        modules.add(hibernate6Module());
        return modules;
    }

    public static Jdk8Module jdk8Module() {
        return new Jdk8Module();
    }

//    public static Hibernate6Module hibernate6Module() {
//        return new Hibernate6Module();
//    }

    public static JavaTimeModule defaultJavaTimeModule() {
        return new JavaTimeModule();
    }

    public static JavaTimeModule configJavaTimeModule() {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT_DEFAULT);
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT_DEFAULT);
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(dateFormatter));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateFormatter));

        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT_DEFAULT);
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(timeFormatter));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(timeFormatter));
        return javaTimeModule;
    }

    public static void safelySetSerialIncludeStrategy(ObjectMapper objectMapper, JsonInclude.Include strategy) {
        if (Objects.nonNull(objectMapper) && Objects.nonNull(strategy)) {
            objectMapper.setSerializationInclusion(strategy);
        }
    }

    public static void safelySetSerialNullListToEmpty(ObjectMapper objectMapper) {
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory()
                .withSerializerModifier(new NullListSerializerModifier()));
    }

    /**
     * @param objectMapper                       {@link ObjectMapper} ObjectMapper对象
     * @param targetClass                        {@link Class} 修改序列化忽略字段的目标类
     * @param withJsonIgnorePropertiesMixInClass {@link Class} 标注了@JsonIgnoreProperties注解的任意类
     * @apiNote 为特定的目标类忽略一些字段
     */
    public static void setFieldSerialIgnore(ObjectMapper objectMapper, Class<?> targetClass, Class<?> withJsonIgnorePropertiesMixInClass) {
        if (Objects.nonNull(objectMapper)) {
            objectMapper.addMixIn(targetClass, withJsonIgnorePropertiesMixInClass);
        }
    }

}
